<?php

namespace app\zyhsapi\model\good_rtc_live;

use app\common\lib\Aes;
use app\zyhsapi\model\BaseCacheZyhs;
use XznsTools\cache\CacheManage;
use XznsTools\cache\zyhs\CacheManageZyhs;

class ZyhsGoodRtcLiveMedia extends BaseCacheZyhs
{
    protected $table = 'good_wechat.zyhs_good_rtc_live_media';

    protected $cacheModel = 'zyhs.good_rtc_live_media';

    /**
     * 批量获取数据
     * @param $ids
     * @param $type
     * @param $sortType
     * @return array|false|string|void
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            $res = $this->alias('m')->join('good_wechat.zyhs_vrtualuser_user u', 'm.vr_id = u.id')->whereIn('m.id', $ids)->order('m.id', 'DESC')->column('m.status,m.sort,m.astr_id,m.vr_id,m.title,m.vid,m.duration,m.bg_img,m.bullet_chat,m.extend,m.create_time,u.avatar,u.nickname', 'm.id');
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return [];
        }

        return $res;
    }

    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        return $this->dataInit($resData);
    }

    /**
     * 数据初始化
     * @param array $data
     * @return array
     */
    public function dataInit(array $data)
    {
        foreach ($data as $index => $itemData)
        {
            $data[$index] = arrayKeyData2int($itemData, ['id', 'status', 'sort', 'astr_id', 'vr_id', 'duration', 'create_time']);
        }

        return $data;
    }

    /**
     * 获取占星师 - 案例列表
     * @param int $astrId
     * @return array
     * @throws \Exception
     */
    public function getAstrCaseList(int $astrId): array
    {
        $dataList = CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('astr_case_list', $astrId)->getDataAndSet(function () use ($astrId)
        {
            $data = $this->where(['astr_id' => $astrId, 'status' => 1])->order('sort desc,id desc')->column('title,vid,duration', 'id');
            foreach ($data as $index => $itemData)
            {
                $data[$index] = json_encode($itemData, JSON_UNESCAPED_UNICODE);
            }
            return $data;
        },[],'astr_case_list');
        $aesType = request()->header('app-type') === 'harmonyos' ? 'harmonyos' : 'app';
        $resData = [];
        foreach ($dataList as $itemData)
        {
            $itemData = json_decode($itemData, true);

            $resData[] = [
                'title' => $itemData['title'],
                'duration' => $itemData['duration'],    //  音频时长
                'audio' => (new Aes())->encryptWithOpenssl($itemData['vid'], $aesType),    //  音频ID【需要AES解密】
            ];
        }
        return $resData;
    }
}
